<template>
    <div class="theme-switch">
        <button
            @click="toggleTheme"
            :class="{'dark-theme': isDarkTheme}"
            class="switch-button"
        >
            <i class="fa fa-moon" :class="{'fa-sun': !isDarkTheme}"></i>
            <i class="fa fa-sun" :class="{'fa-moon':  isDarkTheme}"></i>
            <span class="slider"></span>
        </button>
    </div>
</template>

<script setup>

    const isDarkTheme = ref(false) // 记录当前主题

    const toggleTheme = () => {
        isDarkTheme.value = !isDarkTheme.value
        document.documentElement.classList.toggle('dark-theme', isDarkTheme.value)
        localStorage.setItem('theme', isDarkTheme.value ? 'dark' : 'light')
    }

    const updateTheme = () => {
        const root = document.documentElement
        if (isDarkTheme.value) {
            root.classList.add('dark-theme')
            root.setAttribute('theme', 'dark')
        } else {
            root.classList.remove('dark-theme')
            root.setAttribute('theme', 'light')
        }
    }

    // 生命周期挂载时触发
    onMounted(() => {
        const storedTheme = localStorage.getItem('theme')
        if (storedTheme === 'dark') {
            isDarkTheme.value = true
        }
        updateTheme()
    })

    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
        isDarkTheme.value = e.matches
        updateTheme()
    })
</script>

<style scoped>
    /* 主题切换按钮 */
    .theme-switch {
        margin-left: 10px;
    }

    .switch-button {
        position: relative;
        display: inline-block;
        height: 26px;
        width: 50px;
        background: #ccc;
        border-radius: 34px;
        border: none;
        cursor: pointer;
        transition: all 0.3s;
        margin: 0 15px;
        vertical-align: middle;
    }

    .switch-button.dark-theme {
        background: #18a2b8;
    }
    .fa-moon, .fa-sun {
        margin:0 5px;
    }
    .fa-moon {
        color: #ffffff;
    }
    .fa-sun {
        color: #393d49;
    }
    .slider {
        position: absolute;
        height: 22px;
        width: 22px;
        left: 2px;
        top: 2px;
        background: white;
        border-radius: 50%;
        transition: all 0.3s;
    }

    .switch-button.dark-theme .slider {
        transform: translateX(24px);
    }
</style>
